const Router = require("koa-router");
const mysql = require("mysql");
const routes = new Router();

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "111111",
    database: "goods"
})
connection.connect()
routes.get("/api/list", async (ctx, next) => {
    try {
        const res = await new Promise((resolve, reject) => {
            connection.query("select * from good", function (error, result) {
                if (error) {
                    reject(error.message)
                } else {
                    resolve(result)
                }
            })
        })
        ctx.response.body = {
            code: 1,
            data: res.sort((a, b) => {
                return b.san - a.san
            })
        }
    } catch (error) {
        ctx.response.body = {
            code: 0,
            msg: error
        }
    }
})

routes.post("/api/merchant", async (ctx, next) => {
    try {
        const { id } = ctx.request.body;
        const res = await new Promise((resolve, reject) => {
            connection.query("select * from good where id=?", id, function (error, result) {
                if (error) {
                    reject(error.message)
                } else {
                    resolve(result)
                }
            })
        })

        ctx.response.body = {
            code: 1,
            res
        }
    } catch (error) {
        ctx.response.body = {
            code: 0,
            message: error
        }
    }
})
routes.post("/api/mark", async (ctx, next) => {
    try {
        const { id } = ctx.request.body
        const res = await new Promise((resolve, reject) => {
            connection.query("select san from good where id=?", id, function (error, result) {
                if (error) reject(error)
                resolve(result)
            })
        })
        await new Promise((resolve, reject) => {
            connection.query('update good set san=? where id=?', [Number(res[0].san) + 1, id], function (error, result) {
                if (error) reject(error)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            message: "评分成功"
        }
    } catch (error) {
        ctx.response.body = {
            code: 1,
            message: error.message
        }
    }
})


module.exports = routes